#!/usr/bin/env python
# encoding: utf-8


import hashlib,time,random,decimal,json
from app import db

from app.model import Electronic
from app.model import ElectronicInCart
from app.model import ElectronicInOrder
from app.model import ElectronicInOrderItem

from app.common.libs.Helper import getCurrentDate, getFormatDate

class InOrderService():

    def createOrder(self, user_id, items = None, note = None):
        resp = { 'code':20000,'message':'入库订单创建成功~', 'data':{}}
        try:
            model_order = ElectronicInOrder()
            model_order.order_sn = self.geneOrderSn()
            model_order.user_id = user_id
            model_order.status = 1 # 请求入库
            model_order.note = note
            model_order.updated_time = model_order.created_time = getCurrentDate()
            db.session.add( model_order )
            db.session.commit()
            for item in items:
                tmp_order_item = ElectronicInOrderItem()
                tmp_order_item.electronic_in_order_id = model_order.id
                tmp_order_item.user_id = user_id
                tmp_order_item.count = item['count']
                tmp_order_item.electronic_id = item['electronic_id']
                tmp_order_item.note = note
                tmp_order_item.updated_time = tmp_order_item.created_time = getCurrentDate()
                db.session.add( tmp_order_item )
            db.session.commit()
            resp['data'] = {
                'id' : model_order.id,
                'order_sn' : model_order.order_sn
            }
        except Exception as e:
            db.session.rollback()
            resp['code'] = -1
            resp['message'] = "下单失败请重新下单"
            return resp
        return resp

    def geneOrderSn(self):
        m = hashlib.md5()
        sn = None
        while True:
            str = "%s-%s"%( int( round( time.time() * 1000) ),random.randint( 0,9999999 ) )
            m.update(str.encode("utf-8"))
            sn = m.hexdigest()
            if not ElectronicOutOrder.query.filter_by( order_sn = sn  ).first():
                break
        return sn

    def inStock(self, user_id, order = None, note = None):
        resp = { 'code':20000,'message':'元器件入库成功~', 'data':{}}

        items = db.session.query(ElectronicInOrderItem)\
                                        .filter( ElectronicInOrderItem.electronic_in_order_id == ElectronicInOrder.id )\
                                        .filter( ElectronicInOrder.id== order.id )\
                                        .all()
        electronic_ids = []
        for item in items:
            electronic_ids.append( item.electronic_id)

        note = note if note else ''
        try:
            #为了防止并发库存出问题了，我们坐下select for update
            tmp_electronic_list = db.session.query( Electronic ).filter( Electronic.id.in_( electronic_ids ) )\
                .with_for_update().all()

            # 库存映射
            tmp_electrionic_stock_mapping = {}
            for tmp_item in tmp_electronic_list:
                tmp_electrionic_stock_mapping[ tmp_item.id ] = tmp_item.stock

            for item in items:
                tmp_left_stock =  tmp_electrionic_stock_mapping[ item.electronic_id ]

                tmp_ret = Electronic.query.filter_by( id = item.electronic_id ).update({
                    "stock":int(tmp_left_stock) + int(item.count)
                })
                if not tmp_ret:
                    raise Exception("入库失败，请重新出库")

                in_stock_model = ElectronicInLog()
                in_stock_model.user_id = user_id
                in_stock_model.electronic_id = item.electronic_id
                in_stock_model.count = item.count
                in_stock_model.note = note
                in_stock_model.created_time = getCurrentDate()
                db.session.add(in_stock_model)
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            resp['code'] = -1
            resp['message'] = "入库失败请重新入库"
            return resp
        return resp

    @staticmethod
    def geneOrderSn():
        m = hashlib.md5()
        sn = None
        while True:
            str = "%s-%s"%( int( round( time.time() * 1000) ),random.randint( 0,9999999 ) )
            m.update(str.encode("utf-8"))
            sn = m.hexdigest()
            if not ElectronicInOrder.query.filter_by( order_sn = sn  ).first():
                break
        return sn


